<template>
  <div class="specs-info">
    <el-dialog :title="types=='add'?'新增':'修改'"
    :visible.sync="Show"
    :before-close="close" width="60%">
      <el-form :model="ruleForm" ref="ruleForm" label-width="120px" class="demo-dynamic">
        <el-form-item prop="specsname" label="属性名">
          <el-input v-model="ruleForm.specsname"></el-input>
        </el-form-item>
        <el-form-item label="属性" prop="attrs">
          <div v-for="(item,index) in attrList" :key="index">
            <el-input v-model="attrList[index]" class="attrs"></el-input>
            <el-button type="danger" @click="delSpecs(index)">删除</el-button>
          </div>
          <el-button @click="addDomain" type="success">添加</el-button>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.stop="close">取消</el-button>
        <el-button @click.stop="submit" type="primary">
          确定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addSpecs, editSpecs } from '@/api/index'
export default {
  name: 'MyWin',
  props: ['isShow', 'types'],
  data () {
    return {
      // 属性值的数据，会根据数组的长度 生成不同的输入框
      attrList: [''],
      ruleForm: {
        attrs: [''],
        specsname: '',
        status: '1'
      },
      Show: this.isShow
    }
  },
  methods: {
    close () {
      this.$emit('updates')
    },
    submit () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          this.ruleForm.attrs = this.attrList.join(',') // 转换格式，后台需要字符串
          let res
          // eslint-disable-next-line
          if (this.types == 'add') {
            res = await addSpecs(this.ruleForm)
          } else {
            res = await editSpecs(this.ruleForm)
          }
          // eslint-disable-next-line
          if (res.code == 200) {
            this.$emit('update')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // 调用关闭函数
      this.close()
    },
    setVal (data) {
      // 给表单项赋值
      this.ruleForm = { ...data }
      this.attrList = this.ruleForm.attrs
    },
    addDomain () {
      this.attrList.push('')
    },
    delSpecs (index) {
      // 删除当前属性值
      this.attrList.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.specs-info .attrs {
  width: 80%;
  margin-right: 20px;
  margin-left: 0;
  margin-bottom: 10px;
}
</style>
